#coding=utf-8
#儲存每個筆記節點的資料
#LoNote 1.0之後轉為向前相容=讀取早期資料使用。

import os, uuid, time, sqlite3, shutil

import lonote.sxml as sxml
import lonote.html as html
import lonote.dba as dba
import lonote.tree as tree
import lonote.path as path


class Note(tree.TreeNode):
    '''儲存每個筆記節點的資料
    包含：
        uuid = 以str為格式存放的uuid
        creTime = 以str(小數的秒)為格式存放的建立時間
        order = 以int儲存的排序(在上層節點下)
        path = 為當前節點對應的路徑（不含檔名）
            上面兩個時間需要用'''
    def __init__(self):
        '''path = 當前目標路徑'''
        super().__init__()
        self.uuid = str(uuid.uuid1())
        self.creTime = str(time.mktime(time.localtime()))
        self.modTime = self.creTime
        self.expanded = False     #用來記錄treeView的展開狀況
        self.listExpanded = False #用來紀錄listView的展開狀況
        self.order = 0
        self.page = None   #qwebpage記憶體快照，用來加速讀取
        self.path = ''     #path不用儲存而是動態導入

    def loadFromXmlFile(self, path):
        '''以xml內容更新本Note (註：只應該用在末端節點(通常是新節點)上)
        path = 不含node.xml的路徑名
        成功回傳新的UUID，失敗None'''
        #讀入xml
        xmlPath = os.path.join(path, 'node.xml')
        if os.path.isfile(xmlPath):
            answer = sxml.load(xmlPath ,[
                'nodeid',
                'created_time',
                'modified_time',
                'order',
                'expanded',
                'list_expanded'])
            #設定從xml讀進來的資料
            self.uuid = answer[0]
            self.creTime = answer[1]
            self.modTime = answer[2]
            self.order = int(answer[3])
            self.expanded = bool(int(answer[4]))
            self.listExpanded = bool(int(answer[5]))

            self.path = path #path也別忘記指派
            return self.uuid
        else:
            return None


def oldNotebook2sqlite(newPath ,oldPath):
    '''將舊版的Notebook轉移成sqlite3模式'''
    def load(path, parentID = None):
        '''載入path本身與他下方的所有筆記'''
        note = Note()
        uuid = note.loadFromXmlFile(path)
        if uuid: #表示載入成功，進行處理
            #----資料匯入sqlite----
            name = os.path.basename(path)
            with open(os.path.join(path,'page.html'), mode = 'r', encoding='utf-8') as file:
                content = file.read()
                contentplain = html.totxt(content)
            rowid = conn.execute('insert into notes(name, parentid, cretime, modtime, tree_expanded, list_expanded, ord, content, contentplain) values(?,?,?,?,?,?,?,?,?)',(name, parentID, note.creTime, note.modTime, note.expanded, note.listExpanded, note.order, content, contentplain)).lastrowid
            ID = conn.execute('select id from notes where rowid = ?',(rowid,)).fetchone()['id']
            attPath = os.path.join(path, 'attached')
            embPath = os.path.join(path, 'embedded')
            #記錄外加檔案路徑
            if os.path.isdir(attPath):
                attDict[ID] = attPath
            if os.path.isdir(embPath):
                embDict[ID] = embPath
            #----------------------
        else: #表示這裡不是一個有效節點，不登錄且遞歸的部份放棄
            return ''
        #遞歸部份
        #dirList為path以下所有子目錄(絕對目錄形式)
        dirList = [os.path.join(path, folder) for folder in os.listdir(path) if os.path.isdir(os.path.join(path, folder))]
        if dirList != []: #如果有子目錄要先遍歷
            for p in dirList:
                load(p, ID)
        return note.uuid

    #先做檢查
    if os.path.exists(newPath):
        return False

    #建立目錄，確定路徑
    os.mkdir(newPath)
    os.path.join(newPath, 'notebook.db')

    #----------
    dba.tableinit(path.cal.bookdb(newPath))
    conn = sqlite3.connect(path.cal.bookdb(newPath))
    conn.row_factory = sqlite3.Row
    #紀錄id對應到的原本attach位置，原本位置不存在不用紀錄
    attDict = {}
    embDict = {}
    uuid = load(oldPath)
    conn.commit()
    conn.close()
    #----------
    #把圖與附件搬來：
    for key in attDict:
        shutil.copytree(attDict[key], path.cal.noteatt(newPath, key))
    for key in embDict:
        shutil.copytree(embDict[key], path.cal.noteemb(newPath, key))
    #如果rootPath能讀取成功，則視為整體讀取成功
    if uuid:
        return True
    else:
        return False
